package com.itheima.dao.impl;

import com.itheima.dao.UserDao;
import com.itheima.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

@Repository
public class UserDaoImpl implements UserDao {

    @Autowired
    JdbcTemplate jdbcTemplate;

    @Override
    public int save(User user) {
        String sql = "insert into t_user values(null,?,?,?,?)";
        int count = jdbcTemplate.update(sql,user.getUsername(),user.getBirthday(),
                user.getSex(),user.getAddress());
        return count;
    }

    @Override
    public int update(User user) {
        String sql = "update t_user set username=?,birthday=?,sex=?,address=? where id=?";
        int count = jdbcTemplate.update(sql,user.getUsername(),user.getBirthday(),
                user.getSex(),user.getAddress(),user.getId());
        return count;
    }

    @Override
    public int delete(Integer id) {
        String sql = "delete from t_user where id=?";
        int count = jdbcTemplate.update(sql, id);
        return count;
    }

    @Override
    public List<User> findAll() {
        RowMapper<User> rowMapper = new RowMapper<User>() {
            @Override
            public User mapRow(ResultSet rs, int rowNum) throws SQLException {
                User user = new User();
                user.setId(rs.getInt("id"));
                user.setUsername(rs.getString("username"));
                user.setBirthday(rs.getDate("birthday"));
                user.setSex(rs.getString("sex"));
                user.setAddress(rs.getString("address"));
                return user;
            }
        };
        String sql = "select * from t_user";
        List<User> userList = jdbcTemplate.query(sql, rowMapper);
        return userList;
    }

    @Override
    public User findById(Integer id) {
        String sql = "select * from t_user where id=?";
        User user = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(User.class), id);
        return user;
    }
}
